<template> 
  <div>
    <div id="hall">
      <div class="home-recom">
        <router-link
          :to="{ path: '/machine/' + item.id }"
          class="hplist"
          v-for="(item, index) in machineList"
          :key="index"
        >
            <img src="img/machine.png" v-if="item.runningstate == 1"/>
            <img src="img/machine2.png" v-if="item.runningstate == 0"/>
            <p>
              <span style="border:1px solid green;color:#f60;" v-if="item.operstate == 0">下线</span>
              <span style="border:1px solid red;color:#f60;" v-if="item.operstate == 1">上线</span>
              <span style="border:1px solid yellow;color:#f60;" v-if="item.operstate == 2">维护中</span>
              <span style="border:1px solid black;color:#f60;" v-if="item.operstate == 3">损坏</span>
            &nbsp; {{ item.name }}</p>
        </router-link> 
      </div>
    </div>
    <Topnav></Topnav>
    <Footer></Footer>
  </div>
</template>

<script>
import mqtt from 'mqtt';
import axios from 'axios';  
import Topnav from "./topnav.vue";
import Footer from "./footer.vue";

export default {
  name: 'hall',
  props: {

  },  
  data () {
    return {
      machineList: {
        type: Array,
        default: () => []
      }
    }
  },  
  components: {
    Topnav,
    Footer
  },    
  mounted: function() { 
    this.InitMqtt();    
    this.RefreshAllMachines();
  }, 
  destroyed: function () {
    console.log("Hall leave.");
    this.$GLOBAL.mqttclient.end();
  },
  methods: {
    InitMqtt: function () {
      var self = this;

     var options = {
    //mqtt客户端的id，这里面应该还可以加上其他参数，具体看官方文档
      clientId: 'mqttjs_' + Math.random().toString(16).substr(2, 8),
      //username:'admin',
      //password:'112233',   
    }    

      this.mqttclient = mqtt.connect("ws://127.0.0.1:9001/mqtt",options) // you add a ws:// url here
      this.$GLOBAL.mqttclient = this.mqttclient;

      //建立连接
      this.mqttclient.on('connect', function () {
        console.log("中心服务器连接成功!")

        var subscribes = ['super/machine/goline',
                          'super/machine/offline'];
        //订阅主题 presence
        self.mqttclient.subscribe(subscribes, function (err) {
          if (!err) {
            console.log("中心服务器消息订阅成功!")
          }else{
          //打印错误
            console.log(err)
          }
        })          
      })
      
      //如果连接错误，打印错误
      this.mqttclient.on('error', function (err) {
        console.log(err)
        self.mqttclient.end()
      })

      //如果client订阅主题成功，那么这里就是当接收到自己订阅主题的处理逻辑
      this.mqttclient.on('message', function (topic, message) {
        // message is Buffer,此处就是打印消息的具体内容
        var msg = message.toString();
        var topicstr = topic.toString();

        console.log(topicstr + ":" + msg);

         try{ 
          var params = JSON.parse( message.toString() );

          var userinfo = self.$cookies.get('userinfo');
          if(userinfo != null && userinfo.id == params.playerid) {
             if(topicstr == 'super/machine/goline' || topicstr == 'super/machine/offline') {
                for(var i=0;i<self.machineList.length;i++) {
                  if(self.machineList[i].id == params.machineid) {
                    self.machineList[i].runningstate = params.state;
                    break;
                  }
                }
             }
          }
         }catch(exception){
          console.info(exception.message);
         } 
      })
    },    
    RefreshAllMachines : function () {
      var self = this;
      var userinfo = this.$cookies.get('userinfo');
      if(userinfo == null) {
        this.$router.push({ path: '/Login' });
      } 
      else {
        var location = 'http://cms.o4.com/mobilegetmachines';

        axios.get(location, {
            params: {
              userid: userinfo.id
            }
          })
          .then(function (response) {
            self.machineList = response.data;
          })
          .catch(function (error) {
            console.log(error);
          });
      }
    }
  }  
}
</script>

<style>
.home-recom {
  width: 100%;  
  text-align: center;
}
.hplist {
  width: 48%;
  margin-right: 2%;
  margin-top: 10px;
  float: left;
  background: #f7f7f7;
  display: inline;
  position: relative;
  z-index: 1;
}
.img1 {
  display: block;
  width: 100%;
  z-index: 1
}
</style>
